let a = "9007199254740991";
let b = "1234567899999999999";

// 大数相加
function add(a, b) {
    let maxLength = Math.max(a.length, b.length);
    a = a.padStart(maxLength, 0);
    b = b.padStart(maxLength, 0);

    let temp = 0;
    let f = 0; // 进位
    let sum = "";
    for (let i = maxLength - 1; i >= 0; i--) {
        temp = parseInt(a[i]) + parseInt(b[i]) + f;
        f = Math.floor(temp / 10);
        sum = temp % 10 + sum;
    }
    if (f === 1)
        sum = "1" + sum;
    return sum;
}

// 大数相减
function diff(a, b) {
    if (!a) return b || "0";
    if (!b) return a || "0";
    let carry = 0; // 借位
    const result = [];
    const maxLength = Math.max(a.length, b.length);
    a = a.padStart(maxLength, '0');
    b = b.padStart(maxLength, '0');
    for (let i = maxLength - 1; i >= 0; i--) {
        const sum = parseInt(a[i]) - parseInt(b[i]) + carry;
        if (sum >= 0) {
            carry = 0;
            result.unshift(sum);
        } else {
            carry = -1;
            result.unshift(sum + 10);
        }
    }
    let res = result.join('').replace(/^0+/, '');
    if (res === '')
        return 0;
    if (carry === -1)
        res = '-' + res;
    return res;

}

// 大数相乘
function multiply(a, b) {
    if (a === '0' || b === '0')
        return '0';
    a = a.replace(/^0*/g, '');
    b = b.replace(/^0*/g, '');
    let len1 = a.length;
    let len2 = b.length;
    let res = new Array(len1 + len2).fill(0);
    for (let i = len1 - 1; i >= 0; i--) {
        for (let j = len2 - 1; j >= 0; j--) {
            let sum = parseInt(a[i]) * parseInt(b[i]) + res[i + j + 1];
            res[i + j + 1] = sum % 10;
            res[i + j] += Math.floor(sum / 10);
        }
    }
    return res.join('').replace(/^0*/, '') || '0';
}


// console.log(add(a, b));
// console.log(diff(a, b));
console.log(multiply(a, b));
